/**
 * 设备相关 API
 */
import http from '../utils/request'

export interface Device {
  id: number
  device_code: string
  device_name: string
  device_type: string
  status: string
  location_name?: string
  latitude?: number
  longitude?: number
  materials_level?: number
  last_maintenance_at?: string
  next_maintenance_at?: string
  last_seen_at?: string
  created_at: string
  updated_at: string
}

export interface DeviceListQuery {
  page?: number
  page_size?: number
  search?: string
  device_type?: string
  status?: string
  location?: string
  materials_level_lt?: number
  sort_by?: string
  sort_order?: string
}

export interface DeviceCreate {
  device_code: string
  device_name: string
  device_type: string
  location_name?: string
  latitude?: number
  longitude?: number
}

export interface DeviceUpdate {
  device_name?: string
  location_name?: string
  latitude?: number
  longitude?: number
  firmware_version?: string
  hardware_version?: string
}

export interface DeviceControlRequest {
  commands: Array<{
    command_type: string
    action: string
    params?: Record<string, any>
  }>
  operator?: string
}

export interface SensorData {
  id: number
  device_id: number
  timestamp: string
  data_type: string
  value: number
  unit?: string
  quality: number
  created_at: string
}

// 获取设备列表
export const getDeviceList = (params?: DeviceListQuery) => {
  return http.get('/devices', { params })
}

// 获取设备详情
export const getDeviceDetail = (id: number) => {
  return http.get(`/devices/${id}`)
}

// 创建设备
export const createDevice = (data: DeviceCreate) => {
  return http.post('/devices', data)
}

// 更新设备信息
export const updateDevice = (id: number, data: DeviceUpdate) => {
  return http.put(`/devices/${id}`, data)
}

// 更新设备状态
export const updateDeviceStatus = (id: number, data: {
  status: string
  materials_level?: number
}) => {
  return http.patch(`/devices/${id}/status`, data)
}

// 控制设备
export const controlDevice = (id: number, data: DeviceControlRequest) => {
  return http.post(`/devices/${id}/control`, data)
}

// 获取传感器数据
export const getSensorData = (id: number, params?: {
  data_type?: string
  start_time?: string
  end_time?: string
  page?: number
  page_size?: number
}) => {
  return http.get(`/devices/${id}/sensor-data`, { params })
}

// 删除设备
export const deleteDevice = (id: number) => {
  return http.delete(`/devices/${id}`)
}

// 获取仪表盘统计
export const getDeviceStatistics = () => {
  return http.get('/devices/statistics/dashboard')
}